package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.itheima.conmmon.BaseContext;
import com.itheima.conmmon.R;
import com.itheima.domain.*;
import com.itheima.dto.OrdersDto;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liwanhu
 * @datetime 2021/10/30 21:17
 */
@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetMealService setMealService;

    /**
     * 支付订单
     * @param order
     * @return
     */
    @PostMapping("submit")
    public R<String> submit(@RequestBody Orders order) {
        orderService.Onsubmit(order);
        return R.success("下单成功");
    }

    /**
     * 实战第一天
     * 用户端,订单分页
     * 显示订单的详细信息,菜品个数
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("userPage")
    public R<Page> page(int page, int pageSize) {
        //获取登录用户
        Long userId = BaseContext.getCreatId();
        //创建分页对象
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //查找用户对应的订单信息
        QueryWrapper<Orders> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        qw.orderByDesc("order_time");
        orderService.page(ordersPage, qw);
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        //List<OrdersDto> records = ordersDtoPage.getRecords();
        //获取其中的传输数据
        List<Orders> records = ordersPage.getRecords();
        //遍历数据
        List<OrdersDto> order_id = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            //获取订单id
            Long id = item.getId();
            //在订单明细表中查询关于订单id的各个菜品信息
            QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", id);
            //获取对象
            List<OrderDetail> list = orderDetailService.list(queryWrapper);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(order_id);
        return R.success(ordersDtoPage);
    }

    /**
     * 实战第一天
     * 管理端的订单明细,分页
     *
     * @param page
     * @param pageSize
     * @param number
     * @return
     */
    @GetMapping("page")
    public R<Page> orderPage(int page, int pageSize, String number, String beginTime, String endTime) {
        //创建分页器
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //查询订单信息
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        log.info("开始时间" + beginTime);
        log.info("结束时间" + endTime);

        queryWrapper.eq(number != null, "number", number);
        queryWrapper.between(beginTime != null, "order_time", beginTime, endTime);
        //排序
        queryWrapper.orderByDesc("order_time");
        orderService.page(ordersPage, queryWrapper);

        return R.success(ordersPage);
    }

    /**
     * 实战第一天
     * 管理端订单明细,派送状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> put(@RequestBody Orders orders) {
        log.info(orders.toString());
        //查询订单
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orders.getId());
        //获取订单对象
        Orders ordersOne = orderService.getOne(queryWrapper);
        //改变status值
        ordersOne.setStatus(orders.getStatus());
        orderService.updateById(ordersOne);
        return R.success("修改成功");
    }

    /**
     * 实战第一天
     * 用户端,再来一单
     * @param orders
     * @return
     */
    @PostMapping("again")
    public R<String> again(@RequestBody Orders orders) {
        log.info(orders.toString());
        //查看购物车是否有数据,并清除购物车数据
        QueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new QueryWrapper<>();
        //查询用户的购物车
        shoppingCartQueryWrapper.eq("user_id", BaseContext.getCreatId());
        //删除购物车中的数据
        shoppingCartService.remove(shoppingCartQueryWrapper);
        //查询id对应的订单信息
        QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orders.getId());
        //查询出多条订单详细信息
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
        //遍历订单中获取的菜品对象
        List<ShoppingCart> collect = list.stream().map((item) -> {
            ShoppingCart shoppingCart1 = new ShoppingCart();
            //将菜品信息拷贝到购物车中
            BeanUtils.copyProperties(item, shoppingCart1);
            //并给菜品信息提供对应的用户信息
            shoppingCart1.setUserId(BaseContext.getCreatId());
            /**
             * 优化
             */
            //获取菜品id
            Long dishId = item.getDishId();
            BigDecimal price;
            if (dishId != null) {
                Dish dish = dishService.getById(dishId);
                //ShoppingCart表中获取菜品价格
                price = dish.getPrice();
                //ShoppingCart表中菜品id为空的话获取的则是套餐
            } else {
                //通过套餐id,获取套餐的信息
                Long setmealId = item.getSetmealId();
                Setmeal setmeal = setMealService.getById(setmealId);
                //获取套餐价格
                price = setmeal.getPrice();
            }
            //把价格存入购物车中,因为价格是bigDecimal类型,转换类型

            shoppingCart1.setAmount(new BigDecimal(price.intValue()/100));
            //获取菜品id对应的菜品对象

            return shoppingCart1;
        }).collect(Collectors.toList());
        //把重新获取的订单菜品或套餐信息再加入购物车中
        shoppingCartService.saveBatch(collect);
        return R.success("成功");
    }
}
